package com.cyou.weplay.service.impl;

import com.cyou.weplay.cache.CacheKeys;
import com.cyou.weplay.db.TableTemplate;
import com.cyou.weplay.redis.JedisConnection;
import com.cyou.weplay.redis.JedisConnectionUtils;
import com.cyou.weplay.service.BaseService;
import com.cyou.weplay.service.api.SystemService;
import com.cyou.weplay.service.exception.ServiceException;
import com.cyou.weplay.utils.NumUtils;
import com.cyou.weplay.utils.StringUtils;

import java.sql.Connection;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisCommands;

/**
 * SystemServiceImpl
 *
 * @author zhaomingyu
 */
public class SystemServiceImpl extends BaseService implements SystemService {

    private static final Logger logger = LoggerFactory.getLogger(SystemServiceImpl.class);

    @Override
    public long incrAndGet(final String counterName) throws ServiceException {
        long i = 0;
        String key = CacheKeys.SYSTEM_COUNTER + counterName;
        JedisConnection jedisConn = JedisConnectionUtils.getJedisConnection(jedisPool);
        JedisCommands jedis = jedisConn.getJedisCommands();
        if(!jedis.hexists(key, "current_value")) {
            try {
                //TODO:LOAD FROM DB
                Long currentValue = new TableTemplate<Long>(this.tableShardManager) {
                    
                    @Override
                    protected Long doWork(Connection conn, String shardedTable, String key) throws Exception {
                        QueryRunner query = new QueryRunner();
                        return query.query(conn, "select current_value from " + shardedTable + " where counter_name=?", new ScalarHandler<Long>(), counterName);
                    }
                }.execute("system_counter");
                jedis.hsetnx(key, "current_value", String.valueOf(currentValue + 1001));
            } catch (Exception ex) {
            }
        }

        i = jedis.hincrBy(key, "current_value", 1);
        JedisConnectionUtils.releaseJedisConnection(jedisConn, jedisPool);
        return i;
    }

    @Override
    public String getGlobalVar(String varname) {
        return "WePlayer";
    }

}
